<?php

namespace app\common\command;

use addons\shopro\service\Wallet as WalletService;
use app\admin\model\Children;
use app\admin\model\market\Acceleration;
use app\admin\model\shopro\user\WalletLog;
use app\common\model\shopro\ReleaseLog;
use app\common\model\User;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\exception\HttpResponseException;

class Release extends Command
{
    protected function configure()
    {
        $this->setName('release')->setHelp('每日释放')->setDescription('每日释放');
    }

    protected function execute(Input $input, Output $output)
    {
        $is_release = config('site.is_release');
        if ($is_release == 1) {
            ini_set('memory_limit', "-1");
            $releaseLogModel = new ReleaseLog();
            $count           = $releaseLogModel->whereTime('createtime', 'd')->count();
             if(config('site.tiaoshi') == 1){
                 $count = 0;
             }
            if (!$count) {
                $userModel        = new \app\common\model\User();
                $moneyModel       = new WalletLog();
                $where['score']   = ['gt', 0];
                $where['score_release'] = ['gt',0];
                $where['is_lock'] = 0;
                $userData         = $userModel->where($where)->field('id,nickname,golden,score_release,score,is_old,level,parent_user_id')->select();
                $user_ids         = '';
                if ($userData) {
                    Db::startTrans();
                    try {
                        $lao_release_scale = config('site.lao_release_scale') / 1000; //老会员释放比例
                        $xin_release_scale = config('site.xin_release_scale') / 1000; //新会员释放比例
                        $golen_scale       = config('site.golen_scale') / 100;        //金豆比例
                        $slive_scale       = (100 - config('site.golen_scale')) / 100;//银豆比例
                        $result            = false;
                        $all_score         = 0;
                        $all_golden        = 0;
                        $all_silver        = 0;
                        $user_num          = 0;
                        foreach ($userData as $k => $v) {
//                            $money = $moneyModel->where(['user_id'=>$v['id'],'type'=>'money','event'=>'admin_recharge','amount'=>['gt',0]])->order('id asc')->value('amount');
                            $money = $v->score_release;
                            if ($v->is_old == 1) {
                                if($v->golden >= $money && $money >0){
                                    $release_scale = $lao_release_scale/2;
                                }else{
                                    $release_scale = $lao_release_scale;
                                }

                                $release = bcmul($v->score_release, $release_scale, 2);
                            } else {
                                if($v->golden >= $money && $money > 0){
                                    $release_scale = $xin_release_scale/2;
                                }else{
                                    $release_scale = $xin_release_scale;
                                }
                                $release = bcmul($v->score_release, $release_scale, 2);
                            }
                            if($v->score <= $release){
                                $release = $v->score;
                            }
                            $all_score += $release;
                            $user_num++;
                            $user_ids .= ','.$v->id;
                            $result      = WalletService::change($v->id, 'score', -$release, 'release',
                                ['level' => $v->level, 'parent_user_id' => $v->parent_user_id],
                                '积分补贴');
                            $golden      = bcmul($release, $golen_scale, 2);
                            $all_golden  += $golden;
                            $result      = WalletService::change($v->id, 'golden', $golden, 'release_golden',
                                ['level' => $v->level],
                                '积分补贴');
                            $slive       = bcmul($release, $slive_scale, 2);
                            $all_silver  += $slive;
                            $result      = WalletService::change($v->id, 'silver', $slive, 'release_slive ',
                                ['level' => $v->level],
                                '积分补贴');
                            $this->jicha($v, $release, $v->level);
                        }
                        Db::commit();
                    } catch (HttpResponseException $e) {
                        Db::rollback();
                        $data    = $e->getResponse()->getData();
                        $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
                        echo $message;
//                        format_log_error($e, 'Release.release.HttpResponseException', $message);
                    }
                    if ($result) {
                        $releaseLogModel->user_ids   = trim($user_ids, ',');
                        $releaseLogModel->user_num   = $user_num;
                        $releaseLogModel->all_score  = $all_score;
                        $releaseLogModel->all_golden = $all_golden;
                        $releaseLogModel->all_silver = $all_silver;
                        $releaseLogModel->save();
                    }
                } else {
                    echo "无会员满足释放-----";
                }
            } else {
                echo "今日已释放";
            }

        }
    }

    public function dailifenhong(
        $members,
        $team_amount,
        $currMemberLevel,
        $user_id,
        $currentCommissionLevel = 1,
        $currCommissionReward = 0,
        $currReward = 0.00
    ) {
        $array = [];
        foreach ($members as $v) {
            $currentAgent = User::where(['id' => $v])->find();
            if ($currentAgent) {
                if ($currentAgent->level > $currMemberLevel) {
                    $currentCommissionLevelRule = $this->getCommissionLevelRule($currentAgent->level);
                    if ($currentCommissionLevelRule) {
                        $commission = $this->caculateGoodsCommission($currentCommissionLevelRule, $team_amount);
                        if ($commission > 0) {
                            $currCommissionReward = $commission - $currReward;
                            if ($currCommissionReward > 0) {
                                $accelerate_scale_two = Acceleration::where([
                                    'status' => 1,
                                    'id'     => $currMemberLevel
                                ])->value('accelerate_scale');
                                db('agentreward_log')->insert([
                                    'user_id'              => $v,
                                    'commission'           => $currCommissionReward,
                                    'amount'               => $team_amount,
                                    'level'                => $currentAgent->level,
                                    'accelerate_scale'     => $currentCommissionLevelRule['accelerate_scale'],
                                    'accelerate_scale_two' => $accelerate_scale_two,
                                    'createtime' => time()
                                ]);
                                $currReward           += $currCommissionReward;
                            }
                        }
                    }
                    $currMemberLevel = $currentAgent->level;
                } elseif ($currentAgent->level == $currMemberLevel) {
                    //平级奖规则
                    $user_level = User::where(['id'=>$user_id])->value('level');
                    if($user_level != $currentAgent->level){
                        $currentCommissionLevelRule = $this->getCommissionLevelRule($currentAgent->level);
                        if ($currentCommissionLevelRule) {
                            $commission = $this->caculateGoodsCommission($currentCommissionLevelRule, $team_amount,
                                'parallel_scale');
                            if ($commission > 0) {
                                $currCommissionReward = $commission;
                                if ($currCommissionReward > 0) {
                                    db('agentreward_log')->insert([
                                        'user_id'    => $v,
                                        'commission' => $currCommissionReward,
                                        'amount'     => $team_amount,
                                        'level'      => $user_level,
                                        'type'       => 2,
                                        'createtime' => time()
                                    ]);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 首页
     */
    public function jicha($user, $release, $level)
    {
        $childrenModel = new Children();
        $member_id     = $childrenModel->where(['children_id' => $user['id']])->order('level',
            'asc')->column('member_id');
        $this->dailifenhong($member_id, $release, $level,$user['id']);
    }

    /**
     * 计算对应规则分销佣金
     *
     * @param  int  $commissionRule  分销规则
     * @param  int  $amount  结算价格
     * @param  int  $goodsNum  购买数量
     */
    private function caculateGoodsCommission($commissionRule, $team_amount, $string = 'accelerate_scale')
    {
        $bili       = $commissionRule[$string] / 100;
        $commission = bcmul($team_amount, $bili, 2);
        return $commission;
    }

    /**
     * 获取对应分销商等级、对应层级的商品佣金规则
     */
    public function getCommissionLevelRule($agentLevel)
    {
        $accelerationModel = new Acceleration();
        $jcRules           = $accelerationModel->where(['status' => 1])->select();
        foreach ($jcRules as $v) {
            if ($v['id'] == $agentLevel) {
                return $v;
            }
        }
        return false;
    }

}
